import socket
import threading

def handle_client_socket(client_socket,addr_tuple):
    while True:
        # 5.接收客户端数据
        client_data = client_socket.recv(1024)
        # 判断接收数据的长度为0时，表示客户端已经下线了
        if client_data:
            print("客户端发送数据：",client_data.decode("gbk"))
            # 6.发送数据到客户端
            client_socket.send("hello world".encode("gbk"))
        else:
            print(client_socket, "已经下线了！")
            break
        # 7.关闭访问的客户端套接字
        client_socket.close()

if __name__ == '__main__':
    # 1.创建tcp服务端套接字
    # AF_INET：IPv4
    # AF_INET6：IPv6
    server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    # 设置端口号复用（让服务端程序退出后端口立即释放）
    server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
    # 2.绑定端口号
    server_socket.bind(("", 8989))
    # 3.设置监听
    server_socket.listen(128)
    while True:
        # 4.等待接收客户端连接
        client_socket,addr_tuple = server_socket.accept()
        print(client_socket)
        print(addr_tuple)
        sub_thread = threading.Thread(target=handle_client_socket,args=(client_socket,addr_tuple))
        sub_thread.daemon = True
        sub_thread.start()
    # 8.关闭服务端套接字
    # server_socket.close()

